package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.mapper.ApUserMapper;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是账号登录还是设备登录
        if(StringUtils.isNotBlank(dto.getPhone())&& StringUtils.isNotBlank(dto.getPassword())){
            //账号
            //2:根据用户名去aduser表中查询有效用户 查出来aduser对象
            QueryWrapper<ApUser> queryWrapper =new QueryWrapper<>();
            queryWrapper.lambda().eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = this.getOne(queryWrapper);
            if(apUser!=null){
                //比较密码  当前用户输入密码串+数据库查出来的salt 拼接  生成新的md5密码串 ，比较新密码串和数据库中的密码串  一致 对  反之
                String psw =dto.getPassword()+ apUser.getSalt();
                String newPwd = DigestUtils.md5DigestAsHex(psw.getBytes()); //md5密码串

                if(apUser.getPassword().equals(newPwd)){
                    //比较成功，生成token给前端(token,user)
                    Map<String,Object> map =new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }else{
                    //失败
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"登录手机号不存在");
            }
        }else{
            //设备登录 token 0
            if(dto.getEquipmentId()!=null){
                Map<String,Object> map =new HashMap<>();
                map.put("token", AppJwtUtil.getToken(0l));
                map.put("user",null);
                return ResponseResult.okResult(map);
            }
        }
        return null;
    }
}
